﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
namespace ImageGet
{
    public partial class Form1 : Form
    {
        //private static readonly string connectionString = "server=60.12.117.90;User Id=uzhubo;password=uzhuboclient.*;Database=uzhubo;Charset=utf8;connect timeout=30";
         private static readonly string connectionString = "server=127.0.0.1;User Id=root;password=root;Database=test;Charset=utf8;connect timeout=7220";




        MySqlConnection m_connection = new MySqlConnection(connectionString);

        MySqlCommand m_command = new MySqlCommand();

        bool collect = false;//采集开关

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        public static bool HttpDownloadFile(string url, string path)
        {
            try
            {
                // 设置参数
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                //发送请求并获取相应回应数据
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                Stream responseStream = response.GetResponseStream();
                //创建本地文件写入流
                Stream stream = new FileStream(path, FileMode.Create);
                byte[] bArr = new byte[1024];
                int size = responseStream.Read(bArr, 0, (int)bArr.Length);
                while (size > 0)
                {
                    stream.Write(bArr, 0, size);
                    size = responseStream.Read(bArr, 0, (int)bArr.Length);
                }
                stream.Close();
                responseStream.Close();
            }
            catch (WebException e)
            {
                //图片采集失败
                return false;
            }
            return true;
        }
        string imgSave(string url_crc, string imgurl, string pt)
        {
            char[] Curl_crc = url_crc.ToCharArray();
            string savepath = "C:\\phpStudy\\WWW\\haozhubo\\liveimg";
            savepath += "\\" + Curl_crc[Curl_crc.Length - 1];
            savepath += "\\" + Curl_crc[Curl_crc.Length - 2];
            savepath += "\\" + Curl_crc[Curl_crc.Length - 3];
            if (!Directory.Exists(savepath))//这个文件夹不存在
            {
                Directory.CreateDirectory(savepath);
            }
            savepath += "\\" + url_crc + ".jpg";
            if (!File.Exists(savepath))//如果不存在该文件
            {
                if (HttpDownloadFile(imgurl, savepath) == true)
                {
                    return savepath;
                }
                else
                {
                    return "http://hao.cn/tpl/img/default.jpg";
                }
            }
            return savepath;
        }
        public MySqlConnection ConnectionClose()
        {
            if (m_connection.State == ConnectionState.Open)
            {
                m_connection.Close();
            }
            return m_connection;
        }
        public void Dispose()
        {
            ConnectionClose();

            if (m_command != null)
            {
                m_command.Dispose();
            }
            if (m_connection != null)
            {
                m_connection.Dispose();
            }
        }

        public MySqlConnection ConnectionOpen()
        {
            try
            {
                if (m_connection.State == ConnectionState.Closed)
                {
                    m_connection.Open();
                }
            }
            catch (MySqlException ex)
            {
                writeLog("连接数据库异常" + ex.ToString());
                //  MessageBox.Show("连接数据库异常" + ex.ToString());
            }
            return m_connection;
        }
        public int ExecuteNonQuery(MySqlCommand command)
        {
            int resVal;
            try
            {
                command.Connection = ConnectionOpen();
                resVal = command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                writeLog(ex.Message + "ExecuteNonQuery");
                // MessageBox.Show(ex.Message + "ExecuteNonQuery");
                resVal = -1;
            }
            return resVal;
        }

        private void writeLog(string str)
        {
            StreamWriter w = File.AppendText("c:\\imageErrorlog.txt");
            w.Write(System.DateTime.Now.ToString("f") + str + "\r\n\r\n");
            w.Close();
        }

        void ThreadDownImg()
        {//下载图片线程

            UInt32 change = 0;//已下载的图片
            UInt32 error = 0;//下载失败的图片
            UInt32 imageNofind = 0;//未找到的图片
            do
            {
                try
                {
                    if (m_connection.State == ConnectionState.Closed)//当前数据库连接状态是关闭状态
                    {
                        try
                        {
                            m_connection.Open();//打开数据库
                        }
                        catch (Exception ex)
                        {
                            writeLog(ex.Message + "ThreadDownImg 打开数据库");
                            //MessageBox.Show(ex.Message + "ThreadDownImg 打开数据库");
                            // string error = "时间:" + DateTime.Now.ToString("MMddHHMM") + "数据库读取失败\r\n";
                            //richTextBox1.Text = error + richTextBox1.Text;
                            //writeLog(error);
                            return;
                        }
                    }

                    // m_command.CommandText = "SELECT * from mc_live4 where img like \'%http%\' ORDER BY pt ASC ,update_time DESC";//执行的语句
                    m_command.CommandText = "SELECT * FROM mc_live WHERE img  not like \'%hao.cn%\' order by RAND() ";//执行的语句
                    m_command.Connection = m_connection;//所连接的数据库
                    m_command.CommandTimeout = 0;
                    MySqlDataReader reader = m_command.ExecuteReader();//返回结果集

                    UInt32 count = 0;
                    ArrayList imgurl = new ArrayList();
                    ArrayList url_crc = new ArrayList();
                    ArrayList pt = new ArrayList();
                    while (reader.Read() && collect)
                    {
                        count++;
                        imgurl.Add(reader["img"].ToString());
                        url_crc.Add(reader["url_crc"].ToString());
                        pt.Add((int)reader["pt"]);
                    }
                    reader.Close();
                    Dispose();

                    for (int i = 0; i < count && collect; i++)
                    {

                        richTextBox1.Text = imgurl[i].ToString();
                        string savePath;
                        if (imgurl[i].ToString() == "")
                        {
                            savePath = "http://hao.cn/tpl/img/default.jpg";
                            imageNofind++;
                        }
                        else
                        {
                            savePath = imgSave(url_crc[i].ToString(), imgurl[i].ToString(), pt[i].ToString());
                        }
                        if (savePath != "")
                        {
                            savePath = savePath.Replace("\\", "/");
                            try
                            {
                                string urlpath;
                                int item = savePath.IndexOf("/liveimg");
                                if (item >= 0)
                                {
                                    urlpath = @"http://pic.hao.cn" + savePath.Substring(item, savePath.Length - item);
                                }
                                else
                                {
                                    urlpath = savePath;
                                }
                                if (urlpath == "http://hao.cn/tpl/img/default.jpg")
                                {
                                    imageNofind++;
                                }
                                String builderSQL = "Update mc_live set img=" + "'" + urlpath + "'" + "where url_crc=" + "'" + url_crc[i].ToString() + "'";
                                MySqlCommand command = new MySqlCommand(builderSQL.ToString());
                                richTextBox1.Text = builderSQL;
                                int res = ExecuteNonQuery(command);
                                if (res == 1)
                                {
                                    // richTextBox1.Text = System.DateTime.Now.ToString("F") + ":采集到" + savePath + ".\r\n" + richTextBox1.Text;
                                    change++;
                                    label1.Text = "采集成功:" + change + ".采集失败:" + error + "." +  "未找到的图片:" + imageNofind;
                                }
                                Dispose();
                            }
                            catch (Exception ex)
                            {
                                writeLog(ex.ToString() + imgurl[i].ToString());
                                continue;
                            }
                        }
                        else
                        {
                            error++;
                            richTextBox1.Text = imgurl[i].ToString() + "采集失败.\r\n" + richTextBox1.Text;
                            label1.Text = "采集成功:" + change + ". 采集失败:" + error + "." + "未找到的图片:" + imageNofind;
                        }
                    }
                    // writeLog(WriteCount);
                }
                catch (MySqlException ex)
                {
                    writeLog(ex.ToString() + "do");
                    return;
                }
                if (CheckBox.Checked == true)
                {
                    Thread.Sleep(1000 * 60 * 10);//如果开的自动采集 则采集当前轮之后 等待10分钟后继续采集
                }
            } while (collect && CheckBox.Checked == true);

        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (button1.Text == "开始采集")
                {
                    collect = true;
                    button1.Text = "关闭采集";
                    CheckBox.Enabled = false;
                    Thread t = new Thread(ThreadDownImg);
                    t.Start();
                }
                else
                {
                    collect = false;
                    button1.Text = "开始采集";
                    CheckBox.Enabled = true;
                }
            }
            catch (Exception ex)
            {

                writeLog(ex.ToString());
            }
            //if (CheckBox.Checked == true)
            //{
            //    Thread.Sleep(10 * 1000);//如果启动了自动更新 则当前处理完毕之后 每过10分钟更新一次图片
            //    button1_Click(sender, e);
            //}
        }
    }
}
